package com.cy.sc.controller;

import com.cy.sc.pojo.Staff;
import com.cy.sc.service.IStaffService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/staff")
public class StaffController {
    @Autowired
    private IStaffService iStaffService;
    //客户端服务
    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/add")
    //ignoreExceptions 忽略指定异常类型，发生该异常时不进行熔断
    @HystrixCommand(fallbackMethod = "hystrixAdd", ignoreExceptions = {IndexOutOfBoundsException.class})
    public boolean addStaff(Staff staff) {
        if (staff != null && staff.getAge() < 16) {
            //ignoreExceptions当插入非法对象时，熔断器不会工作，方法会报错
            throw new IndexOutOfBoundsException("员工年龄不合法");
        }
        return iStaffService.addStaff(staff);
    }

    @GetMapping("/get/{id}")
    @HystrixCommand(fallbackMethod = "hystrixGet", commandKey = "getCacheKey")
    public Staff getStaffById(@PathVariable("id") long id) {
        //这个方法开启了缓存，在同一请求中缓存生效,调用增加了缓存机制的Service,不管几次只走一次真实查询
        //用来演示Hystrix Cache
        Staff staffById = iStaffService.getStaffById(id);//走查询
        staffById = iStaffService.getStaffById(id);//走缓存
        staffById = iStaffService.getStaffById(id);//走缓存
        staffById = iStaffService.getStaffById(id);//走缓存
        if (staffById == null) {
            throw new RuntimeException("查询不在范围内!");
        }
        return staffById;
    }

    @GetMapping("/list")
    @HystrixCommand(fallbackMethod = "hystrixGetAll")
    public List<Staff> getStaffAll() {
        return iStaffService.getStaffAll();
    }


    //熔断方案 单条查询
    private Staff hystrixGet(@PathVariable("id") long id) {
        return new Staff().setStaffno(id)
                .setSname("id=>" + id + "没有这个员工")
                .setDb_source("no database in mysql");

    }

    //熔断方案 列表查询
    private List<Staff> hystrixGetAll() {
        return new ArrayList();
    }

    //熔断方案 列表查询
    private boolean hystrixAdd(Staff staff) {
        return false;
    }
}
